// 主题类型
export type ThemeType = 'light' | 'dark' | 'auto'

// 编辑器设置
export interface EditorSettings {
  fontSize: number
  fontFamily: string
  lineHeight: number
  tabSize: number
  wordWrap: boolean
  lineNumbers: boolean
  minimap: boolean
  autoSave: boolean
  autoSaveDelay: number
}

// AI设置
export interface AISettings {
  apiKey: string
  model: string
  temperature: number
  maxTokens: number
  autoSuggest: boolean
}

// Git设置
export interface GitSettings {
  userName: string
  userEmail: string
  autoCommit: boolean
  commitTemplate: string
}

// 应用设置
export interface AppSettings {
  theme: ThemeType
  language: string
  sidebarWidth: number
  rightPanelWidth: number
  showStatusBar: boolean
  showLineNumbers: boolean
  enableVimMode: boolean
  enableSpellCheck: boolean
}

// 完整设置接口
export interface UserSettings {
  app: AppSettings
  editor: EditorSettings
  ai: AISettings
  git: GitSettings
}

// 默认设置
const defaultSettings: UserSettings = {
  app: {
    theme: 'auto',
    language: 'zh-CN',
    sidebarWidth: 280,
    rightPanelWidth: 320,
    showStatusBar: true,
    showLineNumbers: true,
    enableVimMode: false,
    enableSpellCheck: true
  },
  editor: {
    fontSize: 14,
    fontFamily: 'SF Mono, Monaco, Consolas, monospace',
    lineHeight: 1.6,
    tabSize: 2,
    wordWrap: true,
    lineNumbers: true,
    minimap: false,
    autoSave: true,
    autoSaveDelay: 2000
  },
  ai: {
    apiKey: '',
    model: 'gpt-3.5-turbo',
    temperature: 0.7,
    maxTokens: 2000,
    autoSuggest: false
  },
  git: {
    userName: '用户',
    userEmail: 'user@example.com',
    autoCommit: false,
    commitTemplate: ''
  }
}

class SettingsService {
  private settings: UserSettings
  private storageKey = 'markdown-editor-settings'
  private listeners: Array<(settings: UserSettings) => void> = []

  constructor() {
    this.settings = this.loadSettings()
    this.applyTheme()
  }

  // 加载设置
  private loadSettings(): UserSettings {
    try {
      const stored = localStorage.getItem(this.storageKey)
      if (stored) {
        const parsed = JSON.parse(stored)
        // 合并默认设置，确保新增的设置项有默认值
        return this.mergeSettings(defaultSettings, parsed)
      }
    } catch (error) {
      console.error('加载设置失败:', error)
    }
    return { ...defaultSettings }
  }

  // 保存设置
  private saveSettings(): void {
    try {
      localStorage.setItem(this.storageKey, JSON.stringify(this.settings))
      this.notifyListeners()
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  }

  // 合并设置
  private mergeSettings(defaults: any, stored: any): any {
    const result = { ...defaults }
    
    for (const key in stored) {
      if (typeof defaults[key] === 'object' && defaults[key] !== null) {
        result[key] = this.mergeSettings(defaults[key], stored[key])
      } else if (stored[key] !== undefined) {
        result[key] = stored[key]
      }
    }
    
    return result
  }

  // 获取所有设置
  getSettings(): UserSettings {
    return { ...this.settings }
  }

  // 获取应用设置
  getAppSettings(): AppSettings {
    return { ...this.settings.app }
  }

  // 获取编辑器设置
  getEditorSettings(): EditorSettings {
    return { ...this.settings.editor }
  }

  // 获取AI设置
  getAISettings(): AISettings {
    return { ...this.settings.ai }
  }

  // 获取Git设置
  getGitSettings(): GitSettings {
    return { ...this.settings.git }
  }

  // 更新应用设置
  updateAppSettings(updates: Partial<AppSettings>): void {
    this.settings.app = { ...this.settings.app, ...updates }
    this.saveSettings()
    
    // 如果主题发生变化，立即应用
    if (updates.theme) {
      this.applyTheme()
    }
  }

  // 更新编辑器设置
  updateEditorSettings(updates: Partial<EditorSettings>): void {
    this.settings.editor = { ...this.settings.editor, ...updates }
    this.saveSettings()
  }

  // 更新AI设置
  updateAISettings(updates: Partial<AISettings>): void {
    this.settings.ai = { ...this.settings.ai, ...updates }
    this.saveSettings()
  }

  // 更新Git设置
  updateGitSettings(updates: Partial<GitSettings>): void {
    this.settings.git = { ...this.settings.git, ...updates }
    this.saveSettings()
  }

  // 重置设置
  resetSettings(): void {
    this.settings = { ...defaultSettings }
    this.saveSettings()
    this.applyTheme()
  }

  // 导出设置
  exportSettings(): string {
    return JSON.stringify(this.settings, null, 2)
  }

  // 导入设置
  importSettings(settingsJson: string): boolean {
    try {
      const imported = JSON.parse(settingsJson)
      this.settings = this.mergeSettings(defaultSettings, imported)
      this.saveSettings()
      this.applyTheme()
      return true
    } catch (error) {
      console.error('导入设置失败:', error)
      return false
    }
  }

  // 应用主题
  private applyTheme(): void {
    const { theme } = this.settings.app
    const root = document.documentElement
    
    // 移除现有主题类
    root.classList.remove('theme-light', 'theme-dark')
    
    if (theme === 'auto') {
      // 自动主题：根据系统偏好
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      root.classList.add(prefersDark ? 'theme-dark' : 'theme-light')
    } else {
      // 手动主题
      root.classList.add(`theme-${theme}`)
    }

    // 更新CSS变量
    this.updateCSSVariables()
  }

  // 更新CSS变量
  private updateCSSVariables(): void {
    const root = document.documentElement
    const { editor } = this.settings
    
    root.style.setProperty('--editor-font-size', `${editor.fontSize}px`)
    root.style.setProperty('--editor-font-family', editor.fontFamily)
    root.style.setProperty('--editor-line-height', editor.lineHeight.toString())
    root.style.setProperty('--sidebar-width', `${this.settings.app.sidebarWidth}px`)
    root.style.setProperty('--right-panel-width', `${this.settings.app.rightPanelWidth}px`)
  }

  // 监听系统主题变化
  watchSystemTheme(): void {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      if (this.settings.app.theme === 'auto') {
        this.applyTheme()
      }
    })
  }

  // 添加设置变化监听器
  addListener(callback: (settings: UserSettings) => void): void {
    this.listeners.push(callback)
  }

  // 移除设置变化监听器
  removeListener(callback: (settings: UserSettings) => void): void {
    const index = this.listeners.indexOf(callback)
    if (index > -1) {
      this.listeners.splice(index, 1)
    }
  }

  // 通知监听器
  private notifyListeners(): void {
    this.listeners.forEach(callback => {
      try {
        callback(this.settings)
      } catch (error) {
        console.error('设置监听器执行失败:', error)
      }
    })
  }

  // 获取当前主题
  getCurrentTheme(): 'light' | 'dark' {
    const { theme } = this.settings.app
    if (theme === 'auto') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
    }
    return theme
  }

  // 切换主题
  toggleTheme(): void {
    const currentTheme = this.getCurrentTheme()
    const newTheme = currentTheme === 'light' ? 'dark' : 'light'
    this.updateAppSettings({ theme: newTheme })
  }

  // 获取快捷键配置
  getKeyboardShortcuts(): Record<string, string> {
    return {
      'Ctrl+N': '新建文件',
      'Ctrl+O': '打开文件',
      'Ctrl+S': '保存文件',
      'Ctrl+Shift+S': '另存为',
      'Ctrl+Z': '撤销',
      'Ctrl+Y': '重做',
      'Ctrl+F': '查找',
      'Ctrl+H': '替换',
      'Ctrl+G': '跳转到行',
      'Ctrl+D': '选择下一个匹配项',
      'Ctrl+Shift+L': '选择所有匹配项',
      'Ctrl+/': '切换注释',
      'Ctrl+Shift+P': '命令面板',
      'Ctrl+`': '切换终端',
      'Ctrl+B': '切换侧边栏',
      'Ctrl+Shift+E': '文件资源管理器',
      'Ctrl+Shift+G': 'Git面板',
      'Ctrl+Shift+A': 'AI助手面板',
      'F11': '全屏模式',
      'Ctrl+Shift+T': '切换主题'
    }
  }
}

// 导出单例实例
export const settingsService = new SettingsService()

// 初始化系统主题监听
settingsService.watchSystemTheme()

// 导出类型
export type { UserSettings, AppSettings, EditorSettings, AISettings, GitSettings }